package com.class05.dao.impl;

import com.class05.dao.StudentDao;
import com.class05.pojo.Student;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

public class StudentDaoImpl implements StudentDao {
    private JdbcTemplate jdbcTemplate;

    //    注入我们的JdbcTemplate对象
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @Override
    public List<Student> findAll() {
//       jdbcTemplate进行数据的查询  ，通过ioc容器进行装配  不需要自己实例化
//        如果pojo实体属性名和数据库字段名不一致，需要使用as关键字进行重命名
        String sql = "select id,name,gender,age,class as classes from students";
        List<Student> stuList = jdbcTemplate.query(sql, new BeanPropertyRowMapper<Student>(Student.class));
//        soutv 打印返回的集合
        System.out.println("stuList = " + stuList);
        return stuList;

    }

    @Override
    public int addStudent(Student student) {
        String sql = "insert into students values(?,?,?,?,?)";
        int update = jdbcTemplate.update(sql, student.getId(),
                student.getName(), student.getGender(),
                student.getAge(), student.getClasses());
        return update;
    }

    @Override
    public int updateStudent(Student student) {
        String sql = "update students set name=?,gender=?,age=?,class=? where id=?";
        int update = jdbcTemplate.update(sql, student.getName(),
                student.getGender(), student.getAge(),
                student.getClasses(), student.getId());
        return update;
    }

    @Override
    public int deleteStudent(Integer id) {
//        ? 占位符，具体值在后面进行填充
        String sql = "delete from students where id=?";
        int update = jdbcTemplate.update(sql, id);
//        如果删除成功，返回1，否则返回0
        return update;
    }
}
